// fit_data_parser.dart

import 'dart:io';
import 'dart:developer';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:fit_tool/fit_tool.dart';

class FitDataParser {
  // ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
  // ★            【全新功能】将 FIT 文件转换为 CSV 字符串            ★
  // ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
  static Future<String> convertFitToCsvString(Uint8List bytes) async {
    try {
      if (bytes.length < 12) {
        return "Error: File is too small to be a valid FIT file.";
      }
      
      final fitFile = FitFile.fromBytes(bytes);
      final stringBuffer = StringBuffer();

      // 1. 动态发现所有存在的字段名作为CSV的表头
      final Set<String> allFieldNames = {};
      for (var record in fitFile.records) {
        final message = record.message;
        if (message is RecordMessage) {
          if (message.timestamp != null) allFieldNames.add('timestamp');
          if (message.distance != null) allFieldNames.add('distance_raw');
          if (message.speed != null) allFieldNames.add('speed_raw');
          if (message.heartRate != null) allFieldNames.add('heart_rate');
          if (message.altitude != null) allFieldNames.add('altitude_raw');
          if (message.cadence != null) allFieldNames.add('cadence');
          if (message.power != null) allFieldNames.add('power');
          if (message.positionLat != null) allFieldNames.add('position_lat');
          if (message.positionLong != null) allFieldNames.add('position_long');
        }
      }
      
      if (allFieldNames.isEmpty) {
        return "Error: No 'RecordMessage' data found in the file.";
      }
      
      final headers = allFieldNames.toList()..sort();
      stringBuffer.writeln(headers.join(',')); // 写入CSV表头

      // 2. 遍历每一条记录，将其转换为CSV的一行
      for (var record in fitFile.records) {
        final message = record.message;
        if (message is RecordMessage) {
          final rowData = <String>[];
          for (var header in headers) {
            String value = ''; // 默认值为空字符串
            switch (header) {
              case 'timestamp': value = message.timestamp?.toString() ?? ''; break;
              case 'distance_raw': value = message.distance?.toString() ?? ''; break;
              case 'speed_raw': value = message.speed?.toString() ?? ''; break;
              case 'heart_rate': value = message.heartRate?.toString() ?? ''; break;
              case 'altitude_raw': value = message.altitude?.toString() ?? ''; break;
              case 'cadence': value = message.cadence?.toString() ?? ''; break;
              case 'power': value = message.power?.toString() ?? ''; break;
              case 'position_lat': value = message.positionLat?.toString() ?? ''; break;
              case 'position_long': value = message.positionLong?.toString() ?? ''; break;
            }
            rowData.add(value);
          }
          stringBuffer.writeln(rowData.join(','));
        }
      }
      
      return stringBuffer.toString();

    } catch (e, stackTrace) {
      log('FIT to CSV conversion failed: $e', name: 'FitDataParser');
      debugPrint('STACK_TRACE: $stackTrace');
      return "Error during conversion: $e";
    }
  }


  // --- 我们之前的所有解析代码保持不变 ---
  static Future<Map<String, dynamic>> analyzeFitFile(File fitFile) async {
    try {
      log('开始分析FIT文件: ${fitFile.path}', name: 'FitDataParser');
      final bytes = await fitFile.readAsBytes();
      return _parseFitBytes(
          bytes, fitFile.path.split(Platform.pathSeparator).last);
    } catch (e, stackTrace) {
      log('FIT文件分析失败: $e', name: 'FitDataParser');
      debugPrint('STACK_TRACE: $stackTrace');
      throw Exception('文件分析过程中出现错误: $e');
    }
  }

  static Future<Map<String, dynamic>> analyzeFitFileBytes(
      Uint8List bytes) async {
    try {
      log('开始分析FIT文件字节 (Web平台)', name: 'FitDataParser');
      return _parseFitBytes(bytes, 'web_selected_file.fit');
    } catch (e, stackTrace) {
      log('FIT文件分析失败: $e', name: 'FitDataParser');
      debugPrint('STACK_TRACE: $stackTrace');
      throw Exception('文件分析过程中出现错误: $e');
    }
  }
// fit-data-parser.dart -> _parseFitBytes (修正后的最终诊断版)

// fit_data_parser.dart -> _parseFitBytes (最终版)

static Future<Map<String, dynamic>> _parseFitBytes(
    Uint8List bytes, String fileName) async {
  try {
    final Map<String, dynamic> fileInfo = {
      'file_name': fileName,
      'file_size': bytes.length,
      'file_type': 'FIT',
      'platform': kIsWeb ? 'Web' : Platform.operatingSystem,
      'is_valid_fit_file': false,
    };

    final fitFile = FitFile.fromBytes(bytes);
    fileInfo['is_valid_fit_file'] = true;

    // --- 变量声明 ---
    final records = <Map<String, dynamic>>[];
    final heartRates = <int>[];
    final speeds = <double>[];
    final altitudes = <double>[];
    final powers = <int>[];
    final cadences = <int>[];
    double totalDistance = 0.0, totalAscent = 0.0;
    double? previousAltitude;
    int? officialCalories;
    int recordMessageCount = 0;
    int? minTimestamp, maxTimestamp;

    // --- 遍历数据 ---
    for (var record in fitFile.records) {
      final message = record.message;

      if (message is SessionMessage) {
        if (message.totalCalories != null) officialCalories = message.totalCalories;
      }
      
      if (message is RecordMessage) {
        recordMessageCount++;
        final recordMap = <String, dynamic>{};
        
        final currentTimestamp = message.timestamp;
        if (currentTimestamp != null) {
           minTimestamp = (minTimestamp == null || currentTimestamp < minTimestamp) ? currentTimestamp : minTimestamp;
           maxTimestamp = (maxTimestamp == null || currentTimestamp > maxTimestamp) ? currentTimestamp : maxTimestamp;
        }

        final speedMs = message.speed; 
        if (speedMs != null) {
          speeds.add(speedMs);
          recordMap['speed'] = speedMs;
        }
        
        final currentDistance = message.distance;
        if (currentDistance != null) { totalDistance = currentDistance; recordMap['distance'] = currentDistance; }
        final heartRate = message.heartRate;
        if (heartRate != null && heartRate > 0) { recordMap['heart_rate'] = heartRate; heartRates.add(heartRate); }
        final altitude = message.altitude;
        if (altitude != null) {
          final altitudeM = altitude / 5.0 - 500;
          altitudes.add(altitudeM); recordMap['altitude'] = altitudeM;
          if (previousAltitude != null && altitudeM > previousAltitude!) { totalAscent += (altitudeM - previousAltitude!); }
          previousAltitude = altitudeM;
        }
        final cadence = message.cadence;
        if (cadence != null && cadence > 0) { recordMap['cadence'] = cadence; cadences.add(cadence); }
        final power = message.power;
        if (power != null && power > 0) { recordMap['power'] = power; powers.add(power); }
        if (recordMap.isNotEmpty) records.add(recordMap);
      }
    }

    // --- 摘要计算 ---
    final summary = <String, dynamic>{};
    
    // 移动时间，我们的"北极星"
    int movingTimeSeconds = recordMessageCount;
    summary['moving_time_seconds'] = movingTimeSeconds;

    // ★★★★★★★★★★★★★★★★★ [最终的核心修正] ★★★★★★★★★★★★★★★★★
    int totalDurationSeconds = 0;
    if (maxTimestamp != null && minTimestamp != null) {
        // 1. 计算出毫秒差
        final diffMilliseconds = maxTimestamp - minTimestamp;
        // 2. 将毫秒差转换为秒 (使用整数除法 `~/`)
        totalDurationSeconds = diffMilliseconds ~/ 1000;
    } else {
        // 如果时间戳无效，安全地回退
        totalDurationSeconds = movingTimeSeconds;
    }
    summary['total_time_seconds'] = totalDurationSeconds;
    // ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    // ... (其他所有摘要计算都已恢复) ...
    summary['total_distance'] = totalDistance;
    if (totalDistance > 0 && movingTimeSeconds > 0) {
      summary['avg_moving_speed'] = totalDistance / movingTimeSeconds; 
    } else {
      summary['avg_moving_speed'] = 0.0;
    }
    summary['max_speed'] = speeds.isNotEmpty ? speeds.reduce((a, b) => a > b ? a : b) : 0.0;
    summary['avg_heart_rate'] = heartRates.isNotEmpty ? (heartRates.reduce((a, b) => a + b) / heartRates.length).round() : 0;
    summary['max_heart_rate'] = heartRates.isNotEmpty ? heartRates.reduce((a, b) => a > b ? a : b) : 0;
    summary['total_ascent'] = totalAscent;
    summary['avg_cadence'] = cadences.isNotEmpty ? (cadences.reduce((a, b) => a + b) / cadences.length).round() : 0;
    summary['max_cadence'] = cadences.isNotEmpty ? cadences.reduce((a, b) => a > b ? a : b) : 0;
    summary['avg_power'] = powers.isNotEmpty ? (powers.reduce((a, b) => a + b) / powers.length).round() : 0;
    summary['max_power'] = powers.isNotEmpty ? powers.reduce((a, b) => a > b ? a : b) : 0;
    summary['calories'] = officialCalories ?? 0;

    const maxDisplayRecords = 500;
    final displayRecords = records.length > maxDisplayRecords ? records.sublist(0, maxDisplayRecords) : records;
    fileInfo['records'] = displayRecords;
    fileInfo['summary'] = summary;
    fileInfo['total_records_parsed'] = records.length;

    log('FIT文件分析完成: 解析了 ${records.length} 条记录', name: 'FitDataParser');
    return fileInfo;
    
  } catch (e, stackTrace) {
    log('FIT文件解析错误: $e', name: 'FitDataParser');
    debugPrint('ERROR_DETAIL: $e');
    debugPrint('STACK_TRACE: $stackTrace');
    return { 'error_message': '文件分析过程中出现错误: $e' };
  }
}



  static bool isValidFitFileHeader(List<int> bytes) {
    if (bytes.length < 12) return false;
    try {
      FitFile.fromBytes(Uint8List.fromList(bytes));
      return true;
    } catch (e) {
      log('FIT文件头验证失败: $e', name: 'FitDataParser');
      return false;
    }
  }
}
